package com.framework.datasources.aspect;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import com.framework.datasources.DataSourceNames;
import com.framework.datasources.DynamicDataSource;
import com.framework.datasources.annotation.DataSource;

/**
 * 多数据源，切面处理类
 */
//开启aop
@Aspect
@Component
public class DataSourceAspect implements Ordered {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	//定义拦截的方法
	@Pointcut("@annotation(com.framework.datasources.annotation.DataSource)")
	public void dataSourcePointCut() {

	}
	//环绕通知,环绕增强，相当于MethodInterceptor，可以设置方法是否执行，以及设置返还信息
	@Around("dataSourcePointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		//方法开始
		//获取方法上的指定注解，注解可能存在可能不存在，不存在就是null。
		MethodSignature signature = (MethodSignature) point.getSignature();
		Method method = signature.getMethod();
		//获取注释
		DataSource ds = method.getAnnotation(DataSource.class);
		if (ds == null) {
			DynamicDataSource.setDataSource(DataSourceNames.FIRST);
			logger.debug("set datasource is " + DataSourceNames.FIRST);
		} else {
			DynamicDataSource.setDataSource(ds.name());
			logger.debug("set datasource is " + ds.name());
		}

		try {
			//运行方法
			return point.proceed();
		} finally {
			//方法结束
			DynamicDataSource.clearDataSource();
			logger.debug("clean datasource");
		}
	}

	@Override
	public int getOrder() {
		return 1;
	}
}
